package com.spark.gaea.bottle.dubbo.utils;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.google.common.base.Preconditions;
import com.spark.gaea.config.service.easyzk.ConfigNode;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.LinkedHashMap;
import java.util.Map;

public class RemoteRpcFactory {
	@Autowired
	private RegistryConfig registryConfig;
	@Autowired
	private ApplicationConfig application;
	@Autowired
	private ConfigNode applicationConfigNode;
	private static Map<String, ReferenceConfig> registryConfigCache;

	public <T> T create(final Class<T> tClass, final String group, final String version) {
		final String addresses = ((ConfigNode) Preconditions.checkNotNull((Object) this.applicationConfigNode,
				"没有配置集中配置地址"))
				.getProperty("dubbo.registry.addresses");
		final String key = addresses + "-" + group + "-" + version;
		ReferenceConfig<T> reference = (ReferenceConfig<T>) RemoteRpcFactory.registryConfigCache.get(key);
		if (null == this.registryConfig) {
			reference = (ReferenceConfig<T>) new ReferenceConfig();
			reference.setApplication(this.application);
			reference.setRegistry(this.registryConfig);
			reference.setInterface(tClass);
			reference.setGroup(group);
			reference.setVersion(version);
			RemoteRpcFactory.registryConfigCache.put(key, reference);
		}
		return reference.get();
	}

	static {
		RemoteRpcFactory.registryConfigCache = new LinkedHashMap<>();
	}
}
